from utils.electrode_ctrl import ElectrodeCtrl
import numpy as np
from time import sleep,time,perf_counter

# 25/July/2024: One board control 16 line-shaped electrodes

def sleep_us(us:float):
    sleep(us / 1_000_000)

# Function to busy-wait for a specified number of microseconds
def busy_wait_us(us: float):
    end_time = perf_counter() + us / 1_000_000  # Calculate end time in seconds
    while perf_counter() < end_time:
        pass  # Busy-wait loop

if __name__=='__main__':
    frame_open = np.zeros((8,8))
    #elec = []
    board=ElectrodeCtrl('COM9', 115200, 'com') # 2号板子（靠近风扇）
    #elec.append(ElectrodeCtrl('COM15', 115200, 'com')) # 1号板子（远离风扇）

    pattern = np.zeros((8,8))

    #U1 fifth row in pattern, facing the character U1 printed on the electrode ,0-7 means scanning from the left to the right electrode
    #U2 sixth row in pattern, facing the character U2 printed on the electrode ,0-7 means scanning from the left to the right electrode
    # 假设U1刺激食指, U2刺激大拇指
    while True:
        for column in range(8):
            count = 0
            print(f'第{column + 1}列，开始扫描，持续1s')
            start_time = perf_counter()  # Record the start time using perf_counter
            while perf_counter() - start_time < 2:  # 持续1秒钟
                # 两个手指的线状电极片，该列刺激持续1s
                for line in range(4, 6):  # index is 4 and 5 (5th and 6th row)
                    if line==4:
                        pattern[line, column] = 1  # 需要两个电极片的column相反，保证刺激产生的方向是一致的
                        print(pattern)
                    if line==5:
                        pattern[line, 7-column] = 1
                        print(pattern)


                    # 取消板子高阻态
                    board.on()
                    board.set_tick(pattern=pattern,
                                   pp=16667,
                                   pw=50,
                                   pn=1,
                                   bp=16667,
                                   pulse_type='neg'
                                   )

                    tick_start_time = perf_counter()
                    # print(tick_start_time)
                    busy_wait_us(16667)  # Busy-wait for 10 microsecond
                    # sleep_us(1000)
                    tick_end_time = perf_counter()
                    # print(tick_end_time)
                    board.off()

                    # Adjust sleep time based on time taken for other operations
                    tick_duration = tick_end_time - tick_start_time
                    # print(f"Tick duration: {tick_duration}")
                    # 将 pattern 的所有元素设置为 0
                    pattern.fill(0)
                count += 1
            print(f'第{line + 1}行 第{column + 1}列 扫描完毕')
            print(f'第{line + 1}行 第{column + 1}列 扫描次数：{count}')



                # # 对于每块板子
                # for index, board in enumerate(elec):
                #
                #     # 取消板子高阻态
                #     board.on()
                #
                #     # 单点，从左扫到右
                #     for i in range(8):
                #         pattern[line, i] = 1
                #         print(f' 第{index + 1}个板子{line + 1}行,第{i + 1}个电极点')
                #         # print(pattern)
                #         board.set_tick(pattern=pattern,
                #                        pp=100,
                #                        pw=50,
                #                        pn=1,
                #                        bp=100,
                #                        pulse_type='neg'
                #                        )
                #
                #         sleep_us(100)
                #         pattern[line, i] = 0


